// *******************************
// HID Serial Example
// Button press
// RAYSHOBBY.net
//
// This program opens an HID serial
// channel and shows the status of
// the pushbutton as it's pressed
// or released. To use it, you need
// to run the HIDSerialMonitor
// from a host computer.
// *******************************
#include<Wire.h>
#include <HIDSerial.h>
#define Addr 0x68
#define BUTTON 4
HIDSerial serial;

void setup() {
  serial.begin();
  pinMode(BUTTON, INPUT);
  digitalWrite(BUTTON, HIGH);
   // Initialise I2C communication as MASTER 
  Wire.begin();
  // Initialise Serial Communication, set baud rate = 9600
  //Serial.begin(9600);

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select Range register
  Wire.write(0x0F);
  // Configure full scale range 2000 dps
  Wire.write(0x80);
  // Stop I2C Transmission
  Wire.endTransmission();

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select Bandwidth register
  Wire.write(0x10);
  // Set bandwidth = 200 Hz
  Wire.write(0x04);
  // Stop I2C Transmission
  Wire.endTransmission();
  //delay(300);
}

void loop() {
  static int last = HIGH;
  static int count = 0;
  int b = digitalRead(BUTTON);
  if(b!=last) {
    serial.print((b==LOW) ? "button down :" : "button up.");
    if (b==LOW) {
      count ++;
      serial.println(count);
    } else {
      serial.println("");
    }
    last = b;
    //delay(50);
  }
  unsigned int data[6];
  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select Gyrometer data register
  Wire.write(0x02);
  // Stop I2C Transmission
  Wire.endTransmission();

  // Request 6 bytes of data
  Wire.requestFrom(Addr, 6);
  // Read 6 bytes of data
  // xGyro lsb, xGyro msb, yGyro lsb, yGyro msb, zGyro lsb, zGyro msb
  if(Wire.available() == 6)
  {
    data[0] = Wire.read();
    data[1] = Wire.read();
    data[2] = Wire.read();
    data[3] = Wire.read();
    data[4] = Wire.read();
    data[5] = Wire.read();
  }  
  // Convert the data
  int xGyro = ((data[1] * 256) + data[0]);
  int yGyro = ((data[3] * 256) + data[2]);
  int zGyro = ((data[5] * 256) + data[4]);
  
  // Output data to the serial monitor
//  serial.print(F("X:"));
  serial.print(xGyro);
  serial.print(F(":"));
  serial.print(yGyro);
  serial.print(F(":"));
  serial.println(zGyro);
  serial.poll();
}
  
